package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.constants.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XZC
 * @since 2024-4-20
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Resource
    private RedissonClient redissonClient;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private static final Integer expectedInsertions = 20;   // 预计插入的数据
    private static final Double fpp = 0.01; //误判率

    @Override
    public Result queryById(Long id) {
        Shop shop = cacheClient.queryWithLogicExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 缓存穿透
        // Shop shop = queryWithPassThrough(id);

        // 互斥锁解决缓存穿透
        // Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存穿透
        // Shop shop = queryWithLogicExpire(id);
        if(shop == null)
            return Result.fail("店铺不存在！");
        return Result.ok(shop);
    }

    /*public Shop queryWithLogicExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 定义布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("bloomfilter");
        bloomFilter.tryInit(expectedInsertions, fpp);
        // 将查询的商铺key存入布隆过滤器（二进制表示）
        // bloomFilter.add(key);
        // 布隆过滤器中不存在店铺id 返回失败
        if (!bloomFilter.contains(key)) {
            return null;
        }

        // 1.判断id在redis中是否存在
        // 2.未命中 直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 3.命中，判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 3.1未逻辑过期 直接返回即可
            return shop;
        }
        // 3.2逻辑过期
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 获取锁成功
            if (expireTime.isAfter(LocalDateTime.now())) {
                // 再次判断是否逻辑过期
                return shop;
            }
            // 开启独立线程重建缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveDataToRedis(id, 20L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                finally {
                    unlock(lockKey);
                }
            });
        }
        // 返回过期的商铺信息(无论获取锁成功/失败）
        return shop;
    }*/

    public void saveDataToRedis(Long id, Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        RedisData data = new RedisData();
        data.setData(shop);
        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(data));
    }

    /*public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("bloomfilter");
        bloomFilter.tryInit(expectedInsertions, fpp);
        // 将查询的商铺key存入布隆过滤器（二进制表示）
        // bloomFilter.add(key);
        // 布隆过滤器中不存在店铺id 返回失败
        if (!bloomFilter.contains(key)) {
            return null;
        }

        // 1.判断id在redis中是否存在
        // 2.命中，如果不为空，直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 3.""空字符串和null两种情况会走到这里，!=null表示为""空字符串。
        if (shopJson != null) {
            return null;
        }

        // 4.获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop;
        try {
            boolean isLock = tryLock(lockKey);
            // 4.1失败 休眠并重试
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4.2成功 再次校验redis中是否有数据
            String shopJson2 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJson2)) {
                return JSONUtil.toBean(shopJson2, Shop.class);
            }
            if (shopJson2 != null) {
                return null;
            }
            // 4.3redis中没有数据，根据id查数据库
            shop = getById(id);
            // 模拟重建延时,检验有多少请求落到数据库（应该只有1个），锁可不可靠
            Thread.sleep(200);
            // 5.数据库不存在,缓存空对象至redis，返回空
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 6.数据库存在，将数据写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7.释放互斥锁
            unlock(lockKey);
        }
        return shop;
    }*/

    /*public Shop queryWithPassThrough(Long id) {
        // 1.获取shopKey
        String shopKey = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("bloomfilter");
        bloomFilter.tryInit(expectedInsertions, fpp);

        // 将查询的商铺key存入布隆过滤器（二进制表示）
        // bloomFilter.add(shopKey);
        // 布隆过滤器中不存在店铺id 返回失败
        if (!bloomFilter.contains(shopKey)) {
            return null;
        }

        // 2.查询Redis看缓存是否存在，StrUtil.isNotBlank()遇见null和""返回false，if不成立继续向下运行
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.命中 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if (shopJson != null) {
            // 返回错误信息,!=null一定是空字符串""
            return null;
        }
        // 4.未命中 查数据库
        Shop shop = getById(id);
        if (shop == null) {
            // 5.数据库查到的也为null，缓存空对象至redis
            stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 6.数据库查到的不为null，写入redis（超时剔除兜底方案）
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }*/

    /*private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }*/

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null) {
            return Result.fail("店铺id不能为空！");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
